<template>
	<view>
		<canvas class="draw-box" @tap="handleTap" canvas-id="draw-box" id="draw-box"></canvas>
	</view>
</template>

<script lang="ts" setup>
	import { ref, onMounted } from 'vue';
	import { deepClone, randomArray } from '../../utils/common-api';
	import { useStudyStore } from '@/store/study';
	const studyStore = useStudyStore();

	/** 单词连线 */
	defineOptions({ name: 'link-word', inheritAttrs: false });
	
	const emit = defineEmits(['next', 'module-event']);
	const drawContainerWidth = ref(0);
	const drawContainerLeft = ref(0);
	const drawContainerTop = ref(0);
	
	// 词汇列表
	const wordList = ref([
		{ Word: 'link word link list context', Mean: '词义1' },
		{ Word: 'word', Mean: '词义2' },
		{ Word: 'link', Mean: '词义3' },
		{ Word: 'list', Mean: '词义4' },
		{ Word: 'context', Mean: '词义5' }
	]);
	// 词汇矩形对象数组
	const leftRectangles = ref([]);
	const rightRectangles = ref([]);
	
	// canvas 画布
	let context = null;
	// 矩形圆角 radius
	const radius = 8;
	
	// 获取画布容器的宽度
	function getDrawContainerWidth(callback: any){
		const query = uni.createSelectorQuery();
		query.select('#draw-box').boundingClientRect()
		.exec(function(res){
			console.log('res[0]', res[0])
			drawContainerWidth.value = res[0].width;
			drawContainerLeft.value = res[0].left;
			drawContainerTop.value = res[0].top;
			
			callback && callback();
		})
	}
	// 初始化画布容器
	function initCanvasContext(){
		context = uni.createCanvasContext('draw-box');
	};
	// 初始化词汇矩形对象数组
	function initWordRectangles() {
		leftRectangles.value = [];
		rightRectangles.value = [];
		
		// 单词选框垂直间距
		const gapY = 30;
		// 左侧单词选框起始点 x
		const leftX = 30;
		// 右侧单词选框起始点 x
		const rightX = 1000;
		// 单词选框宽度
		const rectWidth = 100;
		// 单词选框高度
		const rectHeight = 50;
		const cloneList = deepClone(wordList.value);
		const leftList = randomArray(cloneList);
		const rightList = randomArray(cloneList);
		leftList.forEach((item, index, arr) => {
			const rect: any = { Word: item.Word, Mean: item.Mean };
			if(drawContainerWidth.value >= 1200){
				rect.rectangle = { x: leftX, y: index * (rectHeight + gapY), width: rectWidth, height: rectHeight }
			} else {
				rect.rectangle = { x: leftX, y: index * (rectHeight + gapY), width: rectWidth, height: rectHeight }
			}
			leftRectangles.value.push(rect);
		})
		
		rightList.forEach((item, index, arr) => {
			const rect: any = { Word: item.Word, Mean: item.Mean };
			if(drawContainerWidth.value >= 1200){
				rect.rectangle = { x: rightX, y: index * (rectHeight + gapY), width: rectWidth, height: rectHeight }
			} else {
				rect.rectangle = { x: rightX, y: index * (rectHeight + gapY), width: rectWidth, height: rectHeight }
			}
			rightRectangles.value.push(rect);
		})
	}
	// 开始绘图
	function startDraw(){
		context.setStrokeStyle('#8b8b8c');
		// 绘制左侧单词框
		leftRectangles.value.forEach((item, index) => {
			drawRoundedRect(item.rectangle);
			drawTextInRect(item.Word, item.rectangle);
		})
		// 绘制右侧中午词义框
		rightRectangles.value.forEach((item, index) => {
			drawRoundedRect(item.rectangle);
			drawTextInRect(item.Word, item.rectangle);
		})
		context.draw()
	}
	
	// 向画布中生成矩形选框
	function drawRoundedRect(rectangle: any) {
		const { x, y, width, height, fillStyle = '#fff' } = rectangle;
		console.log('drawRoundedRect')
	    context.beginPath();
	    context.moveTo(x, y + radius); // 开始点
	    context.lineTo(x, y + height - radius); // 顶部直线到顶部圆角起始点
	    context.arcTo(x, y + height, x + radius, y + height, radius); // 顶部圆角
	    context.lineTo(x + width - radius, y + height); // 右侧直线到右侧圆角起始点
	    context.arcTo(x + width, y + height, x + width, y + height - radius, radius); // 右侧圆角
	    context.lineTo(x + width, y + radius); // 底部直线到底部圆角起始点
	    context.arcTo(x + width, y, x + width - radius, y, radius); // 底部圆角
	    context.lineTo(x + radius, y); // 左侧直线到左侧圆角起始点
	    context.arcTo(x, y, x, y + radius, radius); // 左侧圆角
		// 闭合路径
		context.closePath();
		context.setFillStyle(fillStyle);
		context.lineWidth = 2;
	    context.fill();
	    context.stroke();
	}
	
	// 向矩形中填充词汇
	function drawTextInRect(text, rectangle) {
		const {
			x,
			y,
			width,
			height,
			font = '16px Arial',
			color = '#000000',
			align = 'center',
			baseline = 'middle'
		} = rectangle;
		
		context.setFillStyle(color);
		context.setFontSize(font);
		context.setTextAlign(align);
		context.setTextBaseline(baseline);
		
		const textWidth = context.measureText(text).width;
		if(textWidth > width){
			// 自动换行处理
			const words = text.split(' ');
			const lineTextList = [];
			let lineText = '';
			let textY = y;
			const lineHeight = context.measureText('M').width * 1.2;
			words.forEach((item, index) => {
				if(index === 0 || lineText.length === 0){
					if(context.measureText(item).width >= width){
						lineTextList.push(item);
						lineText = '';
					} else {
						lineText = item;
					}
					return;
				}
				
				if(context.measureText(lineText + ' ' + item).width > width){
					lineTextList.push(lineText);
					lineText = item;
					return;
				}
				
				lineText += ' ' + item;
			})
			
			if(lineText.length > 0){
				lineTextList.push(lineText);
				lineText = '';
			}
			
			const lineCount = lineTextList.length;
			// 第一行的起点y的位置
			const fristStartY = (y + height / 2) - (lineCount * lineHeight) / 2;
			const halfHeight = lineHeight / 2;
			
			lineTextList.forEach((item, index) => {
				const rowStartHeight = index * lineHeight;
				const currentX = x + width / 2;
				const currentY = fristStartY + (rowStartHeight + halfHeight);
				context.fillText(item, currentX, currentY);
			})
			
		} else {
			context.fillText(text, x + width / 2, y + height / 2);
		}
	}
	// 检测点击位置是否在矩形内
	function isPointInRect(x, y, rect) {
		return x >= rect.x && 
			   x <= rect.x + rect.width && 
			   y >= rect.y && 
			   y <= rect.y + rect.height;
	}
	
	function handleTap(data){
		// 获取点击的坐标
		const { x, y } = data.detail;
		const leftPointRect = leftRectangles.value.find(rect => {
			return isPointInRect(x - drawContainerLeft.value, y - drawContainerTop.value, rect.rectangle);
		});
		const rightPointRect = rightRectangles.value.find(rect => {
			return isPointInRect(x - drawContainerLeft.value, y - drawContainerTop.value, rect.rectangle);
		});
		
		// 每次改变都是全部重绘，所以不能对单个进行操作
		if(leftPointRect) {
			leftRectangles.value.forEach(item => {
				if(item.ID === leftPointRect.ID){
					if(item.rectangle.isSelected){
						item.rectangle.strokeStyle = '#8b8b8c';
						item.rectangle.fillStyle = '#fff';
						item.rectangle.color = '#000000';
						item.rectangle.isSelected = false;
					} else {
						item.rectangle.strokeStyle = '#ff0000';
						item.rectangle.fillStyle = '#ff0000';
						item.rectangle.color = '#ffffff';
						item.rectangle.isSelected = true;
					}
				}
			})
		}
		if(rightPointRect){
			rightRectangles.value.forEach(item => {
				if(item.ID === leftPointRect.ID){
					if(item.rectangle.isSelected){
						item.rectangle.strokeStyle = '#8b8b8c';
						item.rectangle.fillStyle = '#fff';
						item.rectangle.color = '#000000';
						item.rectangle.isSelected = false;
					} else {
						item.rectangle.strokeStyle = '#ff0000';
						item.rectangle.fillStyle = '#ff0000';
						item.rectangle.color = '#ffffff';
						item.rectangle.isSelected = true;
					}
				}
			})
		}
		
		if(leftPointRect || rightPointRect){
			context.setStrokeStyle('#8b8b8c');
			// 绘制左侧单词框
			leftRectangles.value.forEach((item, index) => {
				drawRoundedRect(item.rectangle);
				drawTextInRect(item.Word, item.rectangle);
			})
			// 绘制右侧中午词义框
			rightRectangles.value.forEach((item, index) => {
				drawRoundedRect(item.rectangle);
				drawTextInRect(item.Word, item.rectangle);
			})
			context.draw()
		}
	}
	
	onMounted(() => {
		getDrawContainerWidth(() => {
			initCanvasContext();
			initWordRectangles();
			startDraw();
		});
	})
</script>

<style lang="scss" scoped>
.draw-box{
	flex: 1;
	height: 100%;
}
</style>